import { useState, useRef } from "react";
import { Image, Button, List, message, Upload } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import useCommonTable from "@/hooks/useCommonTable";
import { fetchList, updateStatus, remove } from "@/api/book";
import { PlusOutlined } from "@ant-design/icons";
import { history } from "umi";
import { disableStatusOptions, filterRasCode } from "@/const";
import useUpdateStatus from "@/hooks/useUpdateStatus";
import { ModalForm, ProFormSelect, ProFormText } from "@ant-design/pro-form";
import ProTable from "@ant-design/pro-table";
import useRemove from "@/hooks/useRemove";
import {
  checkMallBooksRas,
  addMallBooksRas,
  fetchMallBooksRasList,
  removeMallBooksRas,
  importBooksExcel,
} from "@/api/book";

export default () => {
  const actionRef = useRef();
  const [uploading, setUploading] = useState(false);
  const [tabActiveKey, setTabActiveKey] = useState(() => {
    return window.location.hash.split("#").slice(-1)?.[0] || "1";
  });

  const formRef = useRef();
  const actionTableRef = useRef();
  const renderAddStorage = (tableRow, specRow) => {
    return (
      <ModalForm
        formRef={formRef}
        title="库存"
        layout="horizontal"
        trigger={<Button type="primary">添加</Button>}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            formRef.current?.resetFields();
          },
          onSubmit: () => {
            formRef.current?.submit();
          },
        }}
        onFinish={async (values) => {
          const res = await addMallBooksRas({
            mallBooksId: tableRow.id,
            rasGoodsId: tableRow.rasGoodsId,
            specificationId: specRow.id,
            // ...values,
            rasMap: {
              [values.rasCode]: values.rasUrl,
            },
          });
          if (res.data) {
            // 刷新列表
            actionStorageRef.current?.reload();
            actionRef.current?.reload(); // 刷新
            return true;
          }
        }}
      >
        <ProFormText name="rasCode" hidden />
        <ProFormText
          label="芯片码全码值"
          name="rasUrl"
          placeholder="扫码/感应芯片添加"
          onChange={(e) => {
            const rasCode = filterRasCode(e.target.value);
            formRef.current.setFieldsValue({
              rasCode: rasCode,
              rasUrl: e.target.value,
            });
          }}
          rules={[
            { required: true, message: "请输入芯片码全码值" },
            {
              max: 150,
              message: "最长为150位",
            },
          ]}
        />
      </ModalForm>
    );
  };

  const actionStorageRef = useRef();
  const [visible, setVisible] = useState(false);
  const [tableRow, setTableRow] = useState({});
  const [specRow, setSpecRow] = useState({});
  const columnsStorage = [
    {
      title: "芯片码",
      dataIndex: "rasCode",
      colSize: 2,
      fieldProps: {
        placeholder: "输入芯片码搜索",
      },
    },
    {
      title: "芯片全码值",
      dataIndex: "rasUrl",
      colSize: 2,
      fieldProps: {
        placeholder: "输入芯片全码值搜索",
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      width: 200,
      render: (_, record) => {
        return useRemove(
          removeMallBooksRas,
          record,
          actionStorageRef,
          {
            specificationId: specRow.id,
          },
          () => {
            // 刷新列表
            actionRef.current?.reload();
          }
        );
      },
    },
  ];

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      width: 150,
      search: false,
    },
    {
      title: "书名",
      dataIndex: "title",
      width: 150,
    },
    {
      title: "封面",
      dataIndex: "picture",
      width: 150,
      search: false,
      render: (_, record) => {
        return <Image width={100} height={100} src={record.picture} />;
      },
    },
    {
      title: "作者",
      dataIndex: "author",
      width: 150,
      search: false,
    },
    {
      title: "出版社",
      dataIndex: "publishingHouse",
      width: 150,
      search: false,
    },
    {
      title: "规格",
      dataIndex: "label",
      search: false,
      width: 300,
      render: (_, record) => {
        return (
          <List
            itemLayout="horizontal"
            dataSource={record?.mallBooksSpecificationVOS || []}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  title={item.specification}
                  description={
                    <>
                      <div>
                        <span>售价:￥{item.price}</span>
                        <span style={{ margin: "0 10px" }}>
                          VIP价格:￥{item.vipPrice}
                        </span>
                        <span>
                          库存:
                          <a
                            onClick={async () => {
                              const res = await checkMallBooksRas({
                                rasGoodsId: record.rasGoodsId,
                              });
                              if (res.data) {
                                setTableRow(record);
                                console.log("item===", item);
                                setSpecRow(item);
                                setVisible(true);
                              } else {
                                message.warning(
                                  "当前书籍在RSA系统尚未审核通过，无法进行新增书包操作"
                                );
                              }
                            }}
                          >
                            {item.inventory || 0}
                          </a>
                        </span>
                      </div>
                    </>
                  }
                />
              </List.Item>
            )}
          />
        );
      },
    },
    {
      title: "所属分类",
      dataIndex: "mallCategoryNames",
      width: 300,
      search: false,
      render: (_, record) => {
        return record?.mallCategoryNames?.join(",");
      },
    },
    {
      title: "是否上架",
      dataIndex: "onTheShelf",
      valueType: "select",
      width: 150,
      fieldProps: {
        options: disableStatusOptions,
      },
      search: false,
      render: (_, record) => {
        return useUpdateStatus(
          updateStatus,
          record,
          actionRef,
          null,
          false,
          "onTheShelf",
          {
            rasGoodsId: record.rasGoodsId,
          }
        );
      },
    },
  ];

  return (
    <PageContainer
      tabActiveKey={tabActiveKey}
      onTabChange={(key) => {
        setTabActiveKey(key);
        window.location.hash = `#${key}`;
        actionRef.current?.reload();
      }}
      tabList={[
        {
          key: "1",
          tab: "出售中",
        },
        {
          key: "0",
          tab: "仓库",
        },
      ]}
    >
      {useCommonTable({
        actionRef,
        title: "书籍",
        columns,
        modalWidth: 700,
        fetchList,
        remove: tabActiveKey == 0 ? remove : null,
        params: {
          onTheShelf: tabActiveKey,
        },
        toolBarRender: () => {
          return tabActiveKey == 1 ? null : (
            <Upload
              showUploadList={false}
              beforeUpload={async (file) => {
                const formData = new FormData();
                formData.append("file", file);
                setUploading(true);
                const res = await importBooksExcel(formData);
                if (res.data) {
                  message.success("导入成功");
                  actionRef.current?.reload();
                }
                setUploading(false);
              }}
            >
              <Button loading={uploading} type="primary">
                导入
              </Button>
            </Upload>
          );
        },
        onlyColumns: tabActiveKey == 1,
        renderEdit: (record) => {
          return (
            <Button
              key="add"
              type="primary"
              onClick={() => {
                history.push(`/book/index/edit?mallBooksId=${record.id}`);
              }}
            >
              编辑
            </Button>
          );
        },
        renderAdd: () => {
          return tabActiveKey == 1 ? null : (
            <Button
              key="add"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                history.push(`/book/index/edit`);
              }}
            >
              新增书籍
            </Button>
          );
        },
        layout: "horizontal",
        actionColumnWidth: 200,
        showCheckbox: false,
      })}

      <ModalForm
        title="库存"
        layout="horizontal"
        submitter={false}
        visible={visible}
        onVisibleChange={setVisible}
        modalProps={{
          destroyOnClose: true,
        }}
      >
        <ProTable
          actionRef={actionStorageRef}
          options={false}
          columns={columnsStorage}
          params={{ mallBooksId: tableRow.id, specificationId: specRow.id }}
          toolBarRender={() => {
            return renderAddStorage(tableRow, specRow);
          }}
          request={fetchMallBooksRasList}
        />
      </ModalForm>
    </PageContainer>
  );
};
